package com.nstar.graphicsinfo.model
{
	import com.nstar.base.event.RequestEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	工具类名称：新浪微博用户解析类
	组件说明：获取各类用户数量
	开发时间：2010.10.24
	开发人员: Jonny
	*/
	public class SinaUserParser extends EventDispatcher
	{
		public static const PARSE_COMPLETED:String = "parsecompleted";
		private var _url:String = "http://t.sina.com.cn";
		
		private var urlLoader:URLLoader;
		private var _html:String;
		
		private var parseCompleted:Boolean = false;
		private var areaVo:AreaVO = new AreaVO();
		
		public function SinaUserParser(vo:AreaVO)
		{
			areaVo = vo;
		}
		
		public function load(url:String=null):void{
			parseCompleted = false;
			if(url){
				this._url = url;
			}
			
			if(!urlLoader){
				urlLoader = new URLLoader();
			}
			
			urlLoader.load(new URLRequest(_url));
			if(urlLoader.hasEventListener(Event.COMPLETE)==false){
				urlLoader.addEventListener(Event.COMPLETE,urlLoaderHandler);
				urlLoader.addEventListener(IOErrorEvent.IO_ERROR,urlLoaderHandler);
			}
		}
		
		private function urlLoaderHandler(event:Event):void{
			switch(event.type){
				case Event.COMPLETE:
					_html = String(event.target.data);
					var list:Array = getList();
					var count:int = getUserCount(list);
					areaVo.count = count;
					this.dispatchEvent(new RequestEvent(PARSE_COMPLETED,areaVo));
					break;
				case IOErrorEvent.IO_ERROR:
					trace("load "+_url+" error!");
					break;
			}
			parseCompleted = true;
		}
		
		private function getList():Array{
			var result:Array = new Array();
			var article:String = "<ul class=\"famTabList\">";
			var start:int = _html.indexOf(article);
			while(start!=-1){
				var end:int = _html.indexOf("</ul>",start);
				if(end!=-1){
					var topic:String = _html.substring(start+article.length,end);
					result.push(topic);
				}
				
				//从结束处开始
				start = _html.indexOf(article,end);
			}
			return result;
		}
		
		//获取最热门的话题
		public function getUserCount(list:Array):int{
			var result:int = 0;
			for each(var s:String in list){
				var ary:Array = s.split("</li>");
				result += (ary.length-1);
			}	
			return result;
		}
		
	}
}